﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace OpenChart.PublicUnits
{
    public static class DataTableHelper
    {
        /// <summary>
        /// 返回DataTalbe中参数指定列中的最小值
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="columnName">列名称</param>
        /// <returns>最小值</returns>
        public static object GetMinValue(this DataTable table, string columnName)
        {
            string expression = string.Format("MIN({0})", columnName);
            object result = table.Compute(expression, "");
            if (table.Columns[columnName].DataType == typeof(DateTime))
            {
                result = Convert.ToDateTime(result).ToOADate();
            }
            return result;
        }

        /// <summary>
        /// 返回DataTalbe中参数指定列中的最大值
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="columnName">列名称</param>
        /// <returns>最大值</returns>
        public static object GetMaxValue(this DataTable table, string columnName)
        {
            string expression = string.Format("MAX({0})", columnName);
            object result = table.Compute(expression, "");
            if (table.Columns[columnName].DataType == typeof(DateTime))
            {
                result = Convert.ToDateTime(result).ToOADate();
            }
            return result;
        }

        /// <summary>
        /// 返回DataTab中参数制定列数据的和
        /// </summary>
        /// <param name="columnName">列名称</param>
        /// <returns>和</returns>
        internal static object GetSumValue(this DataTable table, string columnName)
        {
            string expression = string.Format("SUM({0})", columnName);
            object result = table.Compute(expression, "");
            if (table.Columns[columnName].DataType == typeof(DateTime))
            {
                result = Convert.ToDateTime(result).ToOADate();
            }
            return result;
        }
    }
}
